package com.app.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.json.JSONObject;
import com.alibaba.excel.EasyExcel;
import com.app.common.SystemConstant;
import com.app.mapper.ApplyMapper;
import com.app.model.AmmunitionModel;
import com.app.model.CategoryModel;
import com.app.model.DepartmentModel;
import com.app.model.OutgoingStatisticsModel;
import com.app.service.OutgoingStatisticsService;
import com.app.util.Result;
import com.app.vo.OutgoingVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@Controller
@RequestMapping("/api/admin/outgoing")
public class OutgoingStatisticsController {
    @Autowired
    private OutgoingStatisticsService outgoingStatisticsService;
    @Autowired
    private ApplyMapper applyMapper;
    //根据单位统计实有数，在位数，外出数：默认今天，可选时间
//    @PostMapping("statistics")
//    public void statistics(@RequestBody JSONObject requestMap,
//                           HttpServletResponse response) throws UnsupportedEncodingException {
//        String startTime = requestMap.getStr("startTime");
//        String endTime = requestMap.getStr("endTime");
//        String file = URLEncoder.encode("单位情况统计_" + "序列" + System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
//
//        String fullPath = System.getProperty("user.dir") + File.separator + "file/export/excel/" + file + ".xlsx";
//        List<OutgoingStatisticsModel> orderUserGroupExportList = this.outgoingStatisticsService.getCountByDepartment(startTime, endTime);
//        String fileName = "人员.xlsx";
//        // 设置响应头信息
//        response.setContentType("application/vnd.ms-excel");
//        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
//        // 输出文件内容到响应流中
//        try (OutputStream outputStream = response.getOutputStream()) {
//            EasyExcel.write(outputStream, OutgoingStatisticsModel.class).sheet("模板").doWrite(orderUserGroupExportList);
//        } catch (IOException e) {
//            // 处理异常
//        }
//    }

    @PostMapping("getStatistics")
    public Result getStatistics(@RequestBody JSONObject requestMap) {
        String startTime = requestMap.getStr("startTime");
        String endTime = requestMap.getStr("endTime");
        List<OutgoingStatisticsModel> orderUserGroupExportList = this.outgoingStatisticsService.getCountByDepartment(startTime, endTime);
        OutgoingStatisticsModel statisticsModel = this.outgoingStatisticsService.getCountTotal(startTime, endTime);
        List<OutgoingStatisticsModel> countByPersonType = this.outgoingStatisticsService.getCountByPersonType(startTime, endTime);
        OutgoingVo vo = new OutgoingVo();
        vo.setList(orderUserGroupExportList);
        vo.setStatisticsModel(Collections.singletonList(statisticsModel));
        vo.setCountByPersonType(countByPersonType);
        return Result.success(vo);
    }

    @PostMapping("/statistics")
    public void exportAmmunitionExcel(@RequestBody JSONObject requestMap, HttpServletResponse response) {
        String startTime = requestMap.getStr("startTime");
        String endTime = requestMap.getStr("endTime");
        Map<String, Object> map = new HashMap<>();
        OutgoingStatisticsModel statisticsModel = this.outgoingStatisticsService.getCountTotal(startTime, endTime);
        List<OutgoingStatisticsModel> countByPersonType = this.outgoingStatisticsService.getCountByPersonType(startTime, endTime);
        List<OutgoingStatisticsModel> countByDepartment = this.outgoingStatisticsService.getCountByDepartment(startTime, endTime);
        for (int i = 0; i < countByDepartment.size(); i++) {
            countByDepartment.get(i).setSeries(i + 1);
        }
        map.put("statisticsModel", Collections.singletonList(statisticsModel));
        map.put("countByPersonType", countByPersonType);
        map.put("countByDepartment", countByDepartment);
        ClassPathResource classPathResource = new ClassPathResource(SystemConstant.out);
        Workbook wb = ExcelExportUtil.exportExcel(new TemplateExportParams(classPathResource.getPath()), map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "外出情况导出表" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}